/**
 * 类型转换工具函数
 * 用于在不同接口格式之间进行数据转换
 */

import type { BabyProfile } from '@/config/supabase';
import type { BabyInfo } from '@/api/baby';
import type { Content } from '@/config/supabase';

/**
 * 将BabyProfile转换为BabyInfo格式
 * @param profile Supabase BabyProfile对象
 * @returns BabyInfo格式的对象
 */
export function convertBabyProfileToBabyInfo(profile: BabyProfile): BabyInfo {
  return {
    id: profile.id,
    user_id: profile.user_id,
    name: profile.name,
    gender: profile.gender,
    birth_date: profile.birth_date,
    weight: profile.weight,
    height: profile.height,
    preferences: profile.preferences,
    created_at: profile.created_at,
    
    // 兼容性字段
    birthDate: profile.birth_date,
    avatar: profile.preferences?.avatar,
    birthWeight: profile.preferences?.birthWeight,
    birthHeight: profile.preferences?.birthHeight,
    currentWeight: profile.weight,
    currentHeight: profile.height,
    notes: profile.preferences?.notes,
    createdAt: profile.created_at
  };
}

/**
 * 将BabyInfo转换为BabyProfile格式
 * @param info BabyInfo对象
 * @returns BabyProfile格式的对象
 */
export function convertBabyInfoToBabyProfile(info: BabyInfo): Omit<BabyProfile, 'id' | 'created_at'> {
  return {
    user_id: info.user_id || '',
    name: info.name,
    gender: info.gender,
    birth_date: info.birth_date || info.birthDate || '',
    weight: info.weight || info.currentWeight,
    height: info.height || info.currentHeight,
    preferences: {
      avatar: info.avatar,
      birthWeight: info.birthWeight,
      birthHeight: info.birthHeight,
      notes: info.notes,
      ...info.preferences
    }
  };
}

/**
 * 计算宝宝年龄
 * @param birthDate 出生日期字符串
 * @returns 年龄描述字符串
 */
export function calculateBabyAge(birthDate: string): string {
  if (!birthDate) return '';
  
  const birth = new Date(birthDate);
  const now = new Date();
  const diffTime = Math.abs(now.getTime() - birth.getTime());
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  
  if (diffDays < 30) {
    return `${diffDays}天`;
  } else if (diffDays < 365) {
    const months = Math.floor(diffDays / 30);
    const days = diffDays % 30;
    return days > 0 ? `${months}个月${days}天` : `${months}个月`;
  } else {
    const years = Math.floor(diffDays / 365);
    const months = Math.floor((diffDays % 365) / 30);
    return months > 0 ? `${years}岁${months}个月` : `${years}岁`;
  }
}

/**
 * 格式化日期为YYYY-MM-DD格式
 * @param date 日期对象或字符串
 * @returns 格式化后的日期字符串
 */
export function formatDate(date: Date | string): string {
  const d = typeof date === 'string' ? new Date(date) : date;
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

/**
 * 安全的数字转换
 * @param value 要转换的值
 * @param defaultValue 默认值
 * @returns 转换后的数字或默认值
 */
export function safeParseFloat(value: any, defaultValue: number = 0): number {
  if (value === null || value === undefined || value === '') {
    return defaultValue;
  }
  const parsed = parseFloat(String(value));
  return isNaN(parsed) ? defaultValue : parsed;
}

/**
 * 安全的整数转换
 * @param value 要转换的值
 * @param defaultValue 默认值
 * @returns 转换后的整数或默认值
 */
export function safeParseInt(value: any, defaultValue: number = 0): number {
  if (value === null || value === undefined || value === '') {
    return defaultValue;
  }
  const parsed = parseInt(String(value), 10);
  return isNaN(parsed) ? defaultValue : parsed;
}

/**
 * 验证必填字段
 * @param obj 要验证的对象
 * @param requiredFields 必填字段数组
 * @returns 验证结果和错误信息
 */
export function validateRequiredFields(
  obj: Record<string, any>, 
  requiredFields: string[]
): { isValid: boolean; missingFields: string[] } {
  const missingFields: string[] = [];
  
  requiredFields.forEach(field => {
    if (!obj[field] || (typeof obj[field] === 'string' && obj[field].trim() === '')) {
      missingFields.push(field);
    }
  });
  
  return {
    isValid: missingFields.length === 0,
    missingFields
  };
}

/**
 * 深度克隆对象
 * @param obj 要克隆的对象
 * @returns 克隆后的对象
 */
export function deepClone<T>(obj: T): T {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }
  
  if (obj instanceof Date) {
    return new Date(obj.getTime()) as unknown as T;
  }
  
  if (obj instanceof Array) {
    return obj.map(item => deepClone(item)) as unknown as T;
  }
  
  if (typeof obj === 'object') {
    const cloned = {} as T;
    Object.keys(obj).forEach(key => {
      (cloned as any)[key] = deepClone((obj as any)[key]);
    });
    return cloned;
  }
  
  return obj;
}

/**
 * 生成唯一ID
 * @param prefix 前缀
 * @returns 唯一ID字符串
 */
export function generateUniqueId(prefix: string = 'id'): string {
  const timestamp = Date.now();
  const random = Math.random().toString(36).substr(2, 9);
  return `${prefix}_${timestamp}_${random}`;
}

/**
 * 防抖函数
 * @param func 要防抖的函数
 * @param delay 延迟时间（毫秒）
 * @returns 防抖后的函数
 */
export function debounce<T extends (...args: any[]) => any>(
  func: T, 
  delay: number
): (...args: Parameters<T>) => void {
  let timeoutId: NodeJS.Timeout;
  
  return (...args: Parameters<T>) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(null, args), delay);
  };
}

/**
 * 节流函数
 * @param func 要节流的函数
 * @param delay 延迟时间（毫秒）
 * @returns 节流后的函数
 */
export function throttle<T extends (...args: any[]) => any>(
  func: T, 
  delay: number
): (...args: Parameters<T>) => void {
  let lastCall = 0;
  
  return (...args: Parameters<T>) => {
    const now = Date.now();
    if (now - lastCall >= delay) {
      lastCall = now;
      func.apply(null, args);
    }
  };
}